package org.brevs.time;

import java.util.Properties;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.appfuse.Constants;
import org.appfuse.dao.RoleDao;
import org.appfuse.dao.UserDao;
import org.appfuse.model.Role;
import org.appfuse.model.User;
import org.appfuse.service.RoleManager;
import org.appfuse.service.UserExistsException;
import org.appfuse.service.UserManager;
import org.brevs.time.dao.ProjectDao;
import org.brevs.time.model.Project;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.security.providers.encoding.PasswordEncoder;

/**
 * Loads some default data in to the database if the db looks empty.
 * @author nick
 *
 */
public class DefaultDataLoader {
	
	private Log log = LogFactory.getLog(this.getClass()); 
	
	private PasswordEncoder passwordEncoder;
	
	private Properties userProperties;
	
	private UserDao userDao;
	
	private RoleDao roleDao;
	
	private ProjectDao projectDao;
	
	@Required
	public void setProjectDao(ProjectDao projectDao) {
		this.projectDao = projectDao;
	}
	
	@Required
	public void setUserProperties(Properties userProperties) {
		this.userProperties = userProperties;
	}
	
	@Required
	public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
		this.passwordEncoder = passwordEncoder;
	}
	
	@Required
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	
	@Required
	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}
	
	public void checkThenLoad() {
		if (dbLooksEmpty()) {
			log.info("Database looks empty, adding default user");
			saveDefaultData();
		}
	}

	private void saveDefaultData() {
		
		Role adminRole = new Role();
		adminRole.setName(Constants.ADMIN_ROLE);
		adminRole.setDescription("Total privileges over the application");
		adminRole = roleDao.save(adminRole);
		
		Role userRole = new Role();
		userRole.setName(Constants.USER_ROLE);
		userRole.setDescription("Normal privileges for someone who wants to access the site");
		userRole = roleDao.save(userRole);
		
		final User user = new User();
    	try {
			BeanUtils.copyProperties(user, userProperties);
		} catch (Exception e) {
			throw new RuntimeException("Unable to set properties " + userProperties + " on user object", e);
		}
		
		user.setPassword(passwordEncoder.encodePassword(user.getPassword(), null));
		user.addRole(userRole);
		user.addRole(adminRole);

		userDao.saveUser(user);
		
		Project project = new Project();
		project.setName("Default Project");
		project.addNewCategory("Default Category");
		
		project = projectDao.save(project);
	}

	private boolean dbLooksEmpty() {
		return userDao.getAll().isEmpty();
	}

}
